package org.piera.diables;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;



public class RestTask extends AsyncTask<HttpUriRequest, Void, String>{

    public static final String HTTP_RESPONSE = "httpResponse";
	
    private Context mContext;
    private String mAction;
    private String mSearchType;
    private static final String DNAME = "diablesdepiera";
	
    public RestTask(Context context, String action, String searchType) {
        mContext = context;
        mAction = action;
        mSearchType = searchType;
        new DefaultHttpClient();
    }
	
    public RestTask(Context context, String action, HttpClient client) {
        mContext = context;
        mAction = action;
    }
	
    @Override
    protected String doInBackground(HttpUriRequest... params) {
        
    	if(mSearchType.equals("gallery")){
    		try{
    			String qResult = null;
    			
                /*HttpUriRequest request = params[0];
                HttpResponse serverResponse = mClient.execute(request);
    			BasicResponseHandler handler = new BasicResponseHandler();
    			String response = handler.handleResponse(serverResponse);
    			parseJsonGallery(response);
                return response;*/
    			
    			HttpClient httpClient = new DefaultHttpClient();
    		    HttpGet httpGet = new HttpGet(params[0].getURI());
    		     
    		    HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
    		     
    		    if (httpEntity != null){
	    		    InputStream inputStream = httpEntity.getContent();
	    		    Reader in = new InputStreamReader(inputStream);
	    		    BufferedReader bufferedreader = new BufferedReader(in);
	    		    StringBuilder stringBuilder = new StringBuilder();
	    		    String stringReadLine = null;
	    		     
	    		    while ((stringReadLine = bufferedreader.readLine()) != null) {
	    		    	stringBuilder.append(stringReadLine + "\n");
	    		    }
	    		     
	    		    qResult = stringBuilder.toString();
	    		    inputStream.close();
    		    }
    			Log.e("Important", qResult);
    		    parseJsonGallery(qResult);
    			return qResult;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
    		
    	}   	
    	
    	return null;
    }
    
    
    private String[] parseJsonGallery(String response) throws IOException{
		   	
    	Storage store = new Storage();
    	    	    	
    	try {
    		  JSONObject JsonObject = new JSONObject(response);
    		  JSONObject Json_photos = JsonObject.getJSONObject("photos");
    		  JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
    		 
    		  //flickrImage = new FlickrImage[JsonArray_photo.length()];
    		  for (int i = 0; i < JsonArray_photo.length(); i++){
    		   JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
    		   /*flickrId = FlickrPhoto.getString("id");
    		   flickrOwner = FlickrPhoto.getString("owner");
    		   flickrSecret = FlickrPhoto.getString("secret");
    		   flickrServer = FlickrPhoto.getString("server");
    		   flickrFarm = FlickrPhoto.getString("farm");
    		   flickrTitle = FlickrPhoto.getString("title");*/
    		   
    		   if(!isDownloaded(FlickrPhoto.getString("id") + "_" + FlickrPhoto.getString("secret") + "_m.jpg")){
    		     		   
	    		   URL url = new URL("http://farm" + FlickrPhoto.getString("farm") + ".static.flickr.com/" + FlickrPhoto.getString("server") + "/" + FlickrPhoto.getString("id") + "_" + FlickrPhoto.getString("secret") + "_m.jpg"); //you can write here any link
	    		   URLConnection ucon = url.openConnection();
	    		   InputStream is = ucon.getInputStream();
	    		   store.saveImage(is, FlickrPhoto.getString("id") + "_" + FlickrPhoto.getString("secret") + "_m.jpg");
	    		   
	    		   Log.v("Test", "http://farm" + FlickrPhoto.getString("farm") + ".static.flickr.com/" + FlickrPhoto.getString("server") + "/" + FlickrPhoto.getString("id") + "_" + FlickrPhoto.getString("secret") + "_m.jpg");
    		   }else{
    			   Log.v("Test", "File "  + FlickrPhoto.getString("id") + "_" + FlickrPhoto.getString("secret") + "_m.jpg is already downloaded");
    		   }
    		   
    		  }
    		  
    		  
    		     		  
    		 } catch (JSONException e) {
    		  // TODO Auto-generated catch block
    		  e.printStackTrace();
    		 }
    	
    	
    	
    	return null;
    	
    }
    
    private boolean isDownloaded(String fileName){
    	File dir = new File("/sdcard/diablesdepiera/");
    	File[] mThumbIds = dir.listFiles();
    	
    	if(!dir.exists()){
    		return false;
    		
    	}else if(dir.listFiles().length != 0){
    		
	    	for (int i = 0; i < mThumbIds.length; i++){	    		
	    		Scanner scanner = new Scanner(mThumbIds[i].toString());	    		 
	    		scanner.findInLine(fileName);	    		 
	    		if (mThumbIds[i].toString().endsWith(fileName)){
	    			Log.v("Test", "file "+ mThumbIds[i].toString() +" already dowloaded");
	    		    return true;//System.out.println(scanner.next());
	    		}	    		
	    	}
    	}
		return false;
    }
	
    @Override
    protected void onPostExecute(String result) {
    	//Storage store = new Storage();
    	//store.saveImage(result,"diables.txt");
        Intent intent = new Intent(mAction);
        
        File dir = new File("/sdcard/diablesdepiera");
        if((dir.exists()) && (dir.listFiles().length != 0)){
	        intent.putExtra(HTTP_RESPONSE, "ok");
	        //Broadcast the completion
        }else{
        	intent.putExtra(HTTP_RESPONSE, "ko");
        }
        mContext.sendBroadcast(intent);
    }
}
